<template>
    <JeepayBackground :bgColorStyle="{ background: '#f7f7f7' }">
        <JeepayCustomNavbar title="会员中心" backCtrl="back" textColor="#fff"
            bgDefaultColor="linear-gradient(270deg, rgb(35, 143, 252) 0%, rgb(26, 102, 255) 100%)" />
        <view class="header-info">
            <view class="member-info">
                <view class="info-main">
                    <text class="num">{{ vdata.mbrTotalCount }}</text>
                    <text class="sub-title">会员总数</text>
                </view>
                <view class="info-main">
                    <view class="num">{{ cal.cert2Dollar(vdata.mbrTotalBalance) }}<text class="unit">元</text></view>
                    <text class="sub-title">会员总余额</text>
                </view>
            </view>
            <view class="nav-list-wrapper">
                <block v-for="(v, i) in navList" :key="i">
                    <view class="nav-item" @tap="toPage(v.pageUrl)">
                        <image :src="v.icon"></image>
                        <text>{{ v.title }}</text>
                    </view>
                </block>
            </view>
        </view>
        <view class="stat-card">
            <view class="time-wrapper">
                <block v-for="(v, i) in timeList" :key="i">
                    <view class="time-item" @tap="changeTime(v.value)"
                        :class="{ 'time-selected': v.value == vdata.selected }">{{
                            v.label }}</view>
                </block>
            </view>
            <view v-show="vdata.selected == 'custom'">
                <view class="time-selection time-custom">
                    <image src="/static/iconImg/custom-time-icon.svg" mode="scaleToFill" />
                    <view class="selection-main" @tap="startTimeRef.show()">{{ vdata.startTime || '请选择开始时间' }} </view>
                    <view>---</view>
                    <view class="selection-main" @tap="endTimeRef.show()">{{ vdata.endTime || '请选择结束时间' }}</view>
                    <image src="/static/iconImg/icon-nav-left.svg" style="transform: rotate(-90deg);" mode="scaleToFill" />
                </view>
            </view>
            <view class="member-consume">
                <text class="num">{{ cal.cert2Dollar(Math.abs(vdata.mbrCount.changeAmount)) }}</text>
                <text class="sub-title">会员消费金额 (元)</text>
            </view>
            <view class="stat-card-info">
                <view class="stat-item">
                    <view class="stat-num">{{ cal.cert2Dollar(vdata.rechargeRecordCount.entryAmount) }}</view>
                    <view class="stat-title">充值入账 (元)</view>
                </view>
                <view class="stat-item">
                    <view class="stat-num">{{ cal.cert2Dollar(vdata.rechargeRecordCount.giveAmount) }}</view>
                    <view class="stat-title">充值赠送 (元)</view>
                </view>
                <view class="stat-item">
                    <view class="stat-num">{{ cal.cert2Dollar(vdata.rechargeRecordCount.payAmount) }}</view>
                    <view class="stat-title">充值支付 (元)</view>
                </view>
                <view class="stat-item">
                    <view class="stat-num">{{ cal.cert2Dollar(Math.abs(vdata.accountHistoryCount.changeAmount)) }}</view>
                    <view class="stat-title">余额变动 (元)</view>
                </view>
                <view class="stat-item">
                    <view class="stat-num">{{ vdata.accountHistoryCount.countNum }}</view>
                    <view class="stat-title">余额变动条数</view>
                </view>
                <view class="stat-item">
                    <view class="stat-num">{{ vdata.mbrCount.changeCount }}</view>
                    <view class="stat-title">会员消费笔数</view>
                </view>
            </view>
        </view>
        <view class="switch-wrapper">
            <block v-for="v in vdata.memberConfig" :key="v.configKey">
                <view class="switch-item" v-if="v.configKey != 'memberModelState'">
                    <text class="switch-text">{{ v.phoneTips.title }}</text>
                    <JeepayStateSwitch v-if="v.configKey != 'mbrMaxBalance'" :confirmTitle="v.phoneTips.tips"
                        :state="v.configVal" showSwitchType @update:state="changeState($event, v)" />
                    <text class="max-amount" v-else>{{ !v.phoneTips.maxAmount ? '不限制充值余额' :  cal.cert2Dollar(v.phoneTips?.maxAmount) }}</text>
                </view>
            </block>
        </view>
    </JeepayBackground>
    <view v-show="vdata.selected == 'custom'">
        <xp-picker ref="startTimeRef" mode="ymd" @confirm="customTime($event, 'startTime')" />
        <xp-picker ref="endTimeRef" mode="ymd" @confirm="customTime($event, 'endTime')" />
    </view>
</template>

<script setup>
import { reactive, ref, onMounted, nextTick } from 'vue'
import { req, API_URL_MEMBERS, API_URL_MEMBER_RECHARGE_RECORDS, API_URL_MEMBER_ACCOUNT_HISTORY, $findOrEditMemberConfig } from '@/http/apiManager.js'
import go from '@/commons/utils/go.js'
import cal from '@/commons/utils/cal.js'
import dayjs from 'dayjs'
import infoBox from '@/commons/utils/infoBox.js'
import { onPullDownRefresh, onShow } from '@dcloudio/uni-app'
const startTimeRef = ref()
const endTimeRef = ref()
const vdata = reactive({
    mbrTotalCount: '', // 会员总数，不随时间条件变化
    mbrTotalBalance: '', // 会员总余额，不随时间条件变化
    mbrCount: {}, // 会员统计
    accountHistoryCount: {}, // 流水统计
    rechargeRecordCount: {}, // 充值统计
    selected: 'today',
    startTime: '',
    endTime: '',
    memberConfig: [] //会员配置项
})

const toPage = (url) => {
    go.to(url)
}

onShow(() => {
    vdata.selected = 'today'
    getMbrCount()
    getMbrStats(vdata.selected)
})

// 导航列表
const navList = [
    {
        title: '会员管理',
        icon: '/static/indexImg/icon-member.svg',
        pageUrl: 'PAGES_MEMBER',
        entId: 'ENT_MCH_MEMBER'
    },
    {
        title: '充值规则',
        icon: '/static/member/recharge-rule.svg',
        pageUrl: 'PAGES_RECHARGE_RULE',
        entId: 'ENT_MEMBER_RECHARGE_RULE'
    },
    {
        title: '账户流水',
        icon: '/static/member/account-history.svg',
        pageUrl: 'PAGES_MEMBER_ACCOUNT_HISTORY',
        entId: 'ENT_MEMBER_ACCOUNT_HISTORY'
    },
    {
        title: '充值记录',
        icon: '/static/member/recharge-record.svg',
        pageUrl: 'PAGES_MEMBER_RECHARGE_RECORD',
        entId: 'ENT_MEMBER_RECHARGE_RECORD'
    },
]
const timeList = [
    { label: '今天', value: 'today' },
    { label: '昨天', value: 'yesterday' },
    { label: '近30天', value: 'near2now_30' },
    { label: '自定义', value: 'custom' }
]
// 下拉刷新
onPullDownRefresh(() => {
    getMbrCount()
    changeTime(vdata.selected)
})

function getMbrCount () {
    // 请求会员统计，不随时间变化
    req.list(API_URL_MEMBERS + '/count', undefined).then(({ bizData }) => {
        uni.stopPullDownRefresh()
        vdata.mbrTotalCount = bizData.memberNum
        vdata.mbrTotalBalance = bizData.balance
    }).catch((err) => uni.stopPullDownRefresh())
}

function getMbrStats (queryDate) {
    const reqParams = {}
    if (queryDate) {
        reqParams.queryDateRange = queryDate
    }

    // 请求会员统计
    req.list(API_URL_MEMBERS + '/count', reqParams).then(({ bizData }) => {
        vdata.mbrCount = bizData
    })

    // 请求记录统计
    req.list(API_URL_MEMBER_RECHARGE_RECORDS + '/count', Object.assign({ state: 2 }, reqParams)).then(({ bizData }) => {
        vdata.rechargeRecordCount = bizData
    })

    // 请求会员流水统计
    req.list(API_URL_MEMBER_ACCOUNT_HISTORY + '/count', reqParams).then(({ bizData }) => {
        vdata.accountHistoryCount = bizData
    })
}

// 切换日期选项，当选自定义时，赋予默认时间
function changeTime (e) {
    if (e != 'custom') {
        vdata.selected = e
        getMbrStats(e)
    } else {
        if (vdata.selected == 'today') {
            vdata.startTime = dayjs().format('YYYY-MM-DD')
            vdata.endTime = dayjs().format('YYYY-MM-DD')

        } else if (vdata.selected == 'yesterday') {
            vdata.startTime = dayjs().subtract(1, 'day').format('YYYY-MM-DD')
            vdata.endTime = dayjs().subtract(1, 'day').format('YYYY-MM-DD')

        } else if (vdata.selected == 'near2now_30') {
            vdata.startTime = dayjs().subtract(30, 'day').format('YYYY-MM-DD')
            vdata.endTime = dayjs().format('YYYY-MM-DD')
        }

        vdata.selected = e
    }
}

function customTime ({ value }, type) {
    if ((type == 'startTime' && dayjs(value).isAfter(dayjs(vdata.endTime)))
        || (type == 'endTime' && (dayjs(vdata.startTime).isAfter(dayjs(value)) || dayjs(value).isAfter(dayjs())))) {
        return infoBox.showToast('时间选择有误')
    }

    vdata[type] = value

    const queryDateRange = `customDateTime_
		${dayjs(vdata.startTime).startOf('date').format('YYYY-MM-DD HH:mm:ss')}_
		${dayjs(vdata.endTime).endOf('date').format('YYYY-MM-DD HH:mm:ss')}`

    getMbrStats(queryDateRange)
}
//移动端自定义提示语
const mebConfig = {
    memberCustomAmountState: {
        title: '是否开启自定义金额充值',
        tips: '是否修改自定义充值金额状态',
        weight: 1
    },
    memberPayState: {
        title: '是否开启会员支付',
        tips: '是否修改会员支付状态',
        weight: 0
    },
    mbrMaxBalance: {
        title: '会员最大储值余额（单位元）',
        tips: '是否修改会员支付状态',
        weight: 2,
        maxAmount: ''
    }
}
// 获取会员支付配置项
const findOrEditMemberConfig = (data, mode, uri) => {
    $findOrEditMemberConfig(data, mode, uri).then(({ bizData }) => {
        if (mode) return infoBox.showToast('修改成功')
        //不需要会员模块
        const index = bizData.findIndex(v => v.configKey == 'memberModelState')
        if (index != '-1') {
            bizData.splice(index, 1)
        }
        bizData.forEach(v => {
            v.phoneTips = mebConfig[v.configKey] || {}
        })
        bizData.sort((a, b) => a.phoneTips.weight - b.phoneTips.weight)
        Object.assign(vdata.memberConfig, bizData)
        findMemberMaxAmount()
    })
}
findOrEditMemberConfig({ groupKey: 'memberConfig' })
function changeState (e, v) {
    v.configVal = e
    findOrEditMemberConfig({ configData: vdata.memberConfig }, 'PUT', '/memberConfig')
}
//查询 会员最大储值金额
function findMemberMaxAmount () {
    $findOrEditMemberConfig(undefined, undefined, '/mbrMaxBalance').then(({ bizData }) => {
        vdata.memberConfig.find(v => v.configKey == 'mbrMaxBalance').phoneTips.maxAmount = bizData
    })
}

</script>

<style lang="scss" scoped>
.time-item {
    display: flex;
    justify-content: center;
    align-items: center;
}

.header-info {
    height: 290rpx;
    background: linear-gradient(270deg, rgb(35, 143, 252) 0%, rgb(26, 102, 255) 100%);
    border: 1rpx solid transparent;
    border-radius: 0 0 32rpx 32rpx;

    .member-info {
        display: flex;
        justify-content: center;
        margin-top: 50rpx;

        .info-main {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            width: 335rpx;
            height: 106rpx;

            .num {
                margin-bottom: 10rpx;
                color: #ffffff;
                font-size: 50rpx;
                font-weight: 500;

                .unit {
                    margin-left: 10rpx;
                    font-size: 22rpx;
                }
            }

            .sub-title {
                color: rgba(255, 255, 255, 0.6);
                font-size: 23rpx;
            }
        }

        view:nth-child(1) {
            border-right: 1rpx solid rgba(255, 255, 255, 0.1);
        }
    }

    .nav-list-wrapper {
        display: flex;
        justify-content: space-between;
        margin: 50rpx auto 40rpx;
        width: 680rpx;
        height: 170rpx;
        border-radius: 32rpx;
        background-color: #fff;

        view {
            width: 170rpx;
            height: 170rpx;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;

            image {
                margin-bottom: 10rpx;
                width: 70rpx;
                height: 70rpx;
            }

            text {
                color: rgba(63, 63, 63, 1);
                font-size: 22rpx;
            }
        }
    }
}

.stat-card {
    margin: 40rpx auto;
    margin-top: 120rpx;
    width: 680rpx;
    min-height: 656rpx;
    border-radius: 32rpx;
    background-color: #fff;
    border: .1rpx solid transparent;

    .time-wrapper {
        display: flex;
        justify-content: space-between;
        margin: 30rpx auto;
        width: 620rpx;
        height: 100rpx;
        border-radius: 20rpx;
        background: linear-gradient(270deg, rgba(35, 143, 252, 0.1) 0%, rgba(26, 102, 255, 0.1) 100%);

        .time-item {
            width: 153.5rpx;
            height: 100rpx;
            border-radius: 20rpx;
            color: rgb(89, 134, 179);
        }

        .time-selected {
            background: linear-gradient(270deg, rgb(35, 143, 252) 0%, rgb(26, 102, 255) 100%);
            color: #fff;
        }
    }
}

.time-selection {
    height: 100rpx;
    white-space: nowrap;

    image {
        width: 40rpx;
        height: 40rpx;
    }

    .selection-main {
        height: auto;
        margin: 0 10rpx 0 20rpx;
        font-size: 30rpx;
        color: rgb(0, 0, 0);
    }
}

.time-custom {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 60rpx;
}

.member-consume {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding-bottom: 50rpx;
    box-shadow: 0 50rpx 70rpx -60rpx rgba(107, 130, 153, 0.2);

    .num {
        margin-top: 50rpx;
        color: rgb(41, 128, 253);
        font-size: 60rpx;
        font-weight: 600;
    }

    .sub-title {
        margin-top: 10rpx;
        color: rgb(166, 166, 166);
        font-size: 24rpx;
    }
}

.stat-card-info {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    padding: 25rpx;

    .stat-item {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        margin: 25rpx 0;
        width: 210rpx;
        height: 82rpx;

        .stat-num {
            margin-bottom: 10rpx;
            color: rgb(0, 0, 0);
            font-size: 30rpx;
            font-weight: 600;
        }

        .stat-title {
            color: rgb(166, 166, 166);
            font-size: 24rpx;
        }
    }
}

.switch-wrapper {
    margin: 40rpx auto 0;
    width: 680rpx;
    height: 330rpx;
    border-radius: 32rpx;
    background: #ffffffff;

    .switch-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 10rpx 0 30rpx;
        height: 110rpx;
    }

    .switch-item:nth-child(2) {
        border-bottom: 1rpx solid rgba(0, 0, 0, 0.06);
        border-top: 1rpx solid rgba(0, 0, 0, 0.06);
    }
}

.max-amount {
    margin-right: 15rpx;
}
</style>
